<template>
  <div>
    <router-view>
      <div class="" v-if="status">
        <div>

          <div class="" style="display: flex;justify-content: space-between; width: 100%;">
            <div>
              <el-button style="margin: 10px" type="primary" @click="addOffice">新增动态</el-button>

            </div>
            <div>
              <el-button style="margin: 10px" type="danger" @click="deleteBatches">批量删除</el-button>
            </div>
          </div>
        </div>
        <el-card class="box-card">
          <template #header>
            <div style="font-size: 20px; font-weight: 600">
              <span>医院动态</span>
            </div>
            <div style="height: 2vh"></div>
            <div style="display: flex; align-items: center">
              <div style="display: flex; align-items: center">
                <el-input style="width: 140px; " v-model="Trendsvalue" @input="searchDepart" placeholder="输入动态名称" />

                <div style="width: 8px"></div>
                <div class="block">
                  <el-date-picker style="width: 240px" v-model="value" type="daterange" range-separator="到"
                    start-placeholder="开始时间" end-placeholder="结束时间" size="default" @change="searchDepart"/>
                </div>
                <!-- <div style="width: 15px"></div> -->
                <div style="width: 15px"></div>

              </div>
              <!-- <el-button :icon="Search" type="primary" @click="searchDepart()">搜索</el-button> -->

              <!-- <el-button type="primary"  @click="searchfilter">搜索</el-button> -->
            </div>
          </template>
          <el-table v-loading="loading" ref="table" :data="pageData" style="width: 100%; margin-bottom: 20px" row-key="id"
            stripe="true" :cell-style="{ textAlign: 'center' }" :header-cell-style="{ 'text-align': 'center' }"
            max-height="68vh">
            <el-table-column type="selection" width="100" fixed="left" />
            <el-table-column prop="id" label="ID" fixed="left" />
            <el-table-column prop="title" label="动态名称" width="350" fixed="left" show-overflow-tooltip />

            <el-table-column prop="heat" label="图片" width="200">
              <!-- <template #default="scope">
              <img class="head_img" :src="url + scope.row.img" alt="" />
            </template> -->
              <template #default="scope">
                <el-image :src="url + scope.row.img" :zoom-rate="1.2" :max-scale="7" :min-scale="0.2"
                  :preview-src-list="[url + scope.row.img]" fit="cover" preview-teleported="true" class="head_img" />
              </template>
            </el-table-column>

            <el-table-column prop="num" label="阅读量" width="200" />

            <!-- <el-table-column prop="details" label="动态描述">
              <template #default="scope">
                <el-tooltip class="box-item" effect="dark" :content="scope.row.parsedDetails" placement="top">
                  <div class="list_word" v-html="scope.row.details"></div>
                </el-tooltip>
              </template>
            </el-table-column> -->
            <el-table-column prop="status" label="是否启用" width="120">
              <template #default="scope">
                <el-switch :value="scope.row.status === 1" @click="affirmSwitch(scope.row)" />
              </template>
            </el-table-column>
            <el-table-column prop="create_time" label="创建时间" width="260" />
            <!-- <el-table-column label="操作" width="100" fixed="right">
            <template #default="scope">
              <img style="width: 20px; height: 20px; margin-right: 10px" src="../../assets/编辑.png" alt=""
                @click="handleEdit(scope.$index, scope.row)" />
              <img style="width: 20px; height: 20px" src="../../assets/删除-01.png" alt=""
                @click="handleDelete(scope.$index, scope.row)" />
            </template>
          </el-table-column> -->
            <el-table-column label="操作" width="150" align="center" fixed="right">
              <template #default="scope">
                <div style="display: flex; align-items: center; justify-content: center">
                  <el-button type="primary" plain size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
                  <el-button type="danger" plain size="small"
                    @click="handleDelete(scope.$index, scope.row)">删除</el-button>
                </div>
              </template>
            </el-table-column>
          </el-table>
          <div style="display: flex; justify-content: center">
            <el-pagination style="padding: 10px" v-model:current-page="currentPage" v-model:page-size="pageSize"
              :page-sizes="[5, 10, 20, 30]" layout="total, sizes,->, prev, pager, next, jumper" :total="listNum"
              @size-change="handleSizeChange" @current-change="handleCurrentChange" />
          </div>
        </el-card>
      </div>
      <!-- 新增/编辑页面 -->
      <el-dialog v-model="dialogFormVisible" :title="form.id <= 0 ? '新增动态信息' : '编辑动态信息'" @close="cancel()" width="50%"
        align-center :close-on-press-escape="false" :close-on-click-modal="false" :show-close="false">
        <div class="window">
          <el-form ref="ruleFormRef" :model="form" :rules="rules" label-width="80px">
            <div class="inpuut_box">
              <div class="box_top">
                <el-form-item label="动态名称" prop="title">
                  <el-input style="width: 300px" v-model="form.title" placeholder="输入动态名称" />
                </el-form-item>
                <el-form-item label="状态" prop="status">
                  <el-switch v-model="form.status" />
                </el-form-item>
                <el-form-item label="阅读量" prop="num">
                  <el-input-number v-model="form.num" :min="1" />
                </el-form-item>
              </div>
              <div class="box_top">
                <el-form-item label="图片" prop="img">
                  <el-upload class="avatar-uploader" :action="url + 'pc/Fileimg/file'" :show-file-list="false"
                    :on-success="handleAvatarSuccess" :on-error="uploadError">
                    <img v-if="form.img" :src="url + form.img" class="avatar" />
                    <el-icon v-else class="avatar-uploader-icon">
                      <Plus />
                    </el-icon>
                  </el-upload>
                </el-form-item>
              </div>
              <div class="box_bottom">
                <el-form-item label="动态介绍" prop="details">
                  <vue-ueditor-wrap style="width: 680px; z-index: 1" v-model="form.details"
                    :config="editorConfig"></vue-ueditor-wrap>
                </el-form-item>
              </div>
            </div>
            <!-- <div style="direction: rtl">
              <el-form-item>
              <el-button type="primary" @click="affirm(ruleFormRef)" v-if="form.id <= 0"
                >新增</el-button
              >
              <el-button type="primary" @click="affirm(ruleFormRef)" v-else>保存</el-button>
              <el-button @click="cancel(ruleFormRef)">取消</el-button>
            </el-form-item>
            </div> -->
            <div style="direction: rtl">
              <el-form-item>
                <el-button type="primary" @click="affirm(ruleFormRef)" v-if="form.id <= 0">新增</el-button>
                <el-button type="primary" @click="affirm(ruleFormRef)" v-else>保存</el-button>
                <div style="height: 10px; width: 10px"></div>
                <el-button @click="cancel(ruleFormRef)">取消</el-button>
              </el-form-item>
            </div>
          </el-form>
        </div>
      </el-dialog>
    </router-view>
  </div>
</template>

<script setup>
import { ref, watchEffect, onMounted, reactive } from 'vue';
import { addTrends, Trends, deleteTrends } from '../../api/trends';
import { Plus, Search } from '@element-plus/icons-vue';
const form = reactive({
  img: '', //图片
  title: '', //动态名称
  details: '', //动态描述
  status: true, //状态
  id: '',
  num: 0,
});
// UEditor配置
const editorConfig = reactive({
  autoHeightEnabled: false,
  initialFrameHeight: 200,
  initialFrameWidth: '100%',
  UEDITOR_HOME_URL: '/ueditor/', // 访问 UEditor 静态资源的根路径publc里面的名称
  serverUrl: '/pc/pc/Fileimg/uderto', // 服务端接⼝
  uploadUrl: '/pc/pc/Fileimg/uderto' + '/kjyl-server-doctor/doctor/file/uploadFile',
  // enableAutoSave: true, // 开启从草稿箱恢复功能需要⼿动设置固定的 editorId，否则组件会默认随机⼀个，如果页⾯刷新，下次渲染的时候 editorId 会重新随机，
});
const dialogFormVisible = ref(false); //弹窗状态
const url = ref('https://lxt.jingyi.icu/'); //域名头
const listNum = ref(0); //列表总数
const currentPage = ref(1); //当前页码数
const classcurrentPage = ref(1); //当前页码数
const pageSize = ref(10); //当前每页显示数量
const classpageSize = ref(10); //当前每页显示数量
const loading = ref(true); //加载状态
const ruleFormRef = ref(); //页面表单实例
const status = ref(true); //编辑添加页的显示隐藏状态
const table = ref(); //表格实例
const TrendsList = ref([]); //动态列表
const classList = ref([]); //动态列表
const Trendsvalue = ref(''); //搜索框内容
const searchData = ref([]); //搜索后列表
const value = ref('');
// 图片上传
const handleAvatarSuccess = (response, uploadFile) => {
  console.log(response);
  console.log(uploadFile);
  form.img = response.data.url;
};
const uploadError = (error, uploadFile) => {
  console.log(error);
  console.log(uploadFile);
  form.img = response.data.url;
};
// 表单效验
const rules = reactive({
  img: [
    {
      required: true,
      message: '请上传图片',
      trigger: 'change',
    },
  ],
  title: [
    {
      required: true,
      message: '请输入动态名称',
      trigger: 'change',
    },
  ],
  details: [
    {
      required: true,
      message: '请输入动态详情',
      trigger: 'change',
    },
  ],
});
//分页数据显示
const pageData = computed(() => {
  console.log();
  let a = [];
  for (
    let i = (currentPage.value - 1) * pageSize.value;
    i < currentPage.value * pageSize.value;
    i++
  ) {
    if (searchData.value[i]) {
      a.push(searchData.value[i]);
    }
  }
  console.log(a);
  return a;
});
//分类列表分页数据显示
const classpageData = computed(() => {
  console.log();
  let a = [];
  for (
    let i = (classcurrentPage.value - 1) * classpageSize.value;
    i < classcurrentPage.value * classpageSize.value;
    i++
  ) {
    if (classList.value[i]) {
      a.push(classList.value[i]);
    }
  }
  console.log(a);
  return a;
});
// 搜索
const searchDepart = () => {
  console.log(value.value);
  searchData.value = TrendsList.value.filter(function (item) {
    let date = new Date(item.create_time).getTime();
    if (value.value) {
      let star = new Date(value.value[0]).getTime();
      let end = new Date(value.value[1]).getTime();
      if (date > star && date < end && item.title.indexOf(Trendsvalue.value) > -1) {
        return item;
      }
    } else {
      if (item.title.indexOf(Trendsvalue.value) > -1) {
        return item;
      }
    }
  });
  listNum.value = searchData.value.length;
};
// 请求列表
const requestList = async () => {
  try {
    const res = await Trends();
    console.log('动态列表', res);
    TrendsList.value = res.data;
    searchDepart();
    loading.value = false;
    if (searchData.value) {
      const parsedData = searchData.value.map(item => {
        const parser = new DOMParser();
        const doc = parser.parseFromString(item.details, 'text/html');
        const textContent = doc.body.innerText;
        return {
          ...item,
          parsedDetails: textContent
        };
      });
      searchData.value = parsedData;
      console.log('初次列表', searchData.value);

    }
  } catch (error) {
    console.error(error);
  }
};
requestList();
// 每页显示数量改变
const handleSizeChange = (val) => {
  pageSize.value = val;
  currentPage.value = 1;
  console.log(`${val} items per page`);
};
// 页码数改变
const handleCurrentChange = (val) => {
  currentPage.value = val;
  console.log(`current page: ${val}`);
};
// 分类页码数改变
const classhandleCurrentChange = (val) => {
  classcurrentPage.value = val;
  console.log(`current page: ${val}`);
};
// 编辑
const handleEdit = (index, row) => {
  dialogFormVisible.value = true;
  form.id = row.id;
  form.title = row.title;
  form.num = row.num;
  form.img = row.img;
  form.details = row.details;
  form.status = row.status == 1 ? true : false;
  console.log(form);
  console.log(index, row);
};
// 删除
const handleDelete = (index, row) => {
  console.log(index, row);
  ElMessageBox.confirm('是否确认删除?', '删除动态', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then((res) => {
      console.log(res);

      deleteTrends({
        id: row.id,
      }).then((result) => {
        console.log(result);
        if (result.code == 0) {
          ElMessage({
            type: 'danger',
            message: result.msg,
          });
        } else if (result.code == 1) {
          ElMessage({
            type: 'success',
            message: '删除成功',
          });
          requestList();
        }
      });
    })
    .catch((res) => {
      console.log(res);
      ElMessage({
        type: 'info',
        message: '取消删除',
      });
    });
};
// // 批量删除
// const deleteBatches = () => {
//   ElMessageBox.confirm('是否确认删除?', '删除动态', {
//     confirmButtonText: '确认',
//     cancelButtonText: '取消',
//     type: 'warning',
//   })
//     .then((res) => {

//     })
//     .catch((res) => {
//       console.log(res);
//       ElMessage({
//         type: 'info',
//         message: '取消删除',
//       });
//     });
// };
const deleteBatches = () => {
  let arr = table.value.getSelectionRows();
  if (arr.length === 0) {
    ElMessage({
      type: 'warning',
      message: '请选中需要删除的数据',
    });
  } else {
    ElMessageBox.confirm('是否确认删除?', '删除动态', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    })
      .then((res) => {
        console.log(res);
        let arr = table.value.getSelectionRows();
        let arrs = [];
        console.log(arr);
        // 构造一个 Promise 数组，每个 Promise 表示一条记录的删除操作
        const promises = arr.map((element) => {
          return deleteTrends({ id: element.id });
        });
        // 使用 Promise.all() 处理 Promise 数组，一旦其中有一个Promise被拒绝（即删除失败），就会执行catch()方法，
        // 否则，如果所有的Promise都得到了解决（即删除成功），就会执行then()方法。
        Promise.all(promises)
          .then((results) => {
            console.log(results);
            results.forEach((result) => {
              if (result.code == 0) {
                ElMessage({
                  type: 'danger',
                  message: result.msg,
                });
              } else if (result.code == 1) {
                arrs.push(result.data);
              }
            });
            if (arrs.length == arr.length) {
              ElMessage({
                type: 'success',
                message: '删除成功',
              });
            } else {
              ElMessage({
                type: 'warning',
                message: '删除失败，请重试',
              });
            }
            requestList();
          })
          .catch((error) => {
            console.log(error);
            ElMessage({
              type: 'warning',
              message: '删除失败，请重试',
            });
          });
      })
      .catch((res) => {
        console.log(res);
        ElMessage({
          type: 'info',
          message: '取消删除',
        });
      });
  }
};

// 新增
const addOffice = () => {
  form.id = '';
  clearForm();
  dialogFormVisible.value = true;
  ruleFormRef.value.clearValidate();
};
// 清空表单
const clearForm = () => {
  form.img = '';
  form.title = '';
  form.num = '';
  form.details = '';
  form.status = true;
};
// 取消
const cancel = (formEl) => {
  clearForm();
  dialogFormVisible.value = false;
  formEl.clearValidate();
};
// 确认新增/编辑
const affirm = async (formEl) => {
  console.log(form);
  if (form.status) {
    form.status = 1;
  } else {
    form.status = 2;
  }
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      addTrends(form).then((res) => {
        console.log(res);
        if (form.id) {
          ElMessage({
            type: 'success',
            message: '编辑成功',
          });
        } else {
          ElMessage({
            type: 'success',
            message: '添加成功',
          });
        }
        dialogFormVisible.value = false;
        clearForm();
        requestList();
      });
      console.log('submit!');
    } else {
      console.log('error submit!', fields);
    }
  });
};
// 列表状态编辑
const affirmSwitch = (data) => {
  console.log(data);
  if (data.status == 1) {
    data.status = 2;
  } else {
    data.status = 1;
  }

  addTrends(data).then((res) => {
    console.log(res);
    if (res.code == 0) {
      ElMessage({
        type: 'danger',
        message: '状态更改失败',
      });
    } else {
      ElMessage({
        type: 'success',
        message: '状态更改成功',
      });
    }

    requestList();
  });
};
</script>

<style lang="scss" scoped>
.box {
  width: 100%;
  background-color: rgb(255, 255, 255);
  overflow-y: scroll;
}

.left {
  max-width: 650px;
  display: flex;
  flex-wrap: wrap;
  align-items: center;
}

.right {
  max-width: 300px;
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  justify-content: center;
}

.header {
  width: 100%;
  display: flex;
  justify-content: space-between;
  padding: 10px 20px;
}

.head_word {
  width: 100%;
  padding: 10px 20px;
  border-bottom: 1px solid #e5e5e5;
  margin-bottom: 20px;
  color: #427eff;
}

.window {
  // width: 80%;
  // overflow-x: scroll;
  padding: 10px;
  background-color: white;
}

.hint {
  margin-left: 10px;
  color: #a6a6a6;
  font-size: 14px;
}

.head_img {
  // width: 40px;
  height: 40px;
  // border-radius: 40px;
}

.lable {
  width: 100%;
  line-height: 1;
  border-radius: 50px;
  padding: 10px;
}

// .list_word {
//   width: 100%;
//   display: -webkit-box;
//   -webkit-line-clamp: 2;
//   -webkit-box-orient: vertical;
//   overflow: hidden;
//   text-overflow: ellipsis;
// }
.list_word {
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 2;
  overflow: hidden;
  text-overflow: ellipsis;
  word-wrap: break-word;
}

// .inpuut_box {
//   width: 800px;
//   display: flex;
//   flex-wrap: wrap;
// }
.box_top {
  width: 400px;
}

.box_bottom {
  width: 800px;
}

//上传
.avatar-uploader {
  border: 1px dashed var(--el-border-color) !important;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  display: flex;
  align-items: center;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}

//上传
.form_word {
  margin-right: 20px;
}

.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}

.list_word {
  width: 100%;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
  text-overflow: ellipsis;
}
</style>
